package com.yue.jmx.demo2;

import javax.management.*;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2017/1/3<br/>
 *
 * @author QiuYang
 */
public class MessageEngine extends NotificationBroadcasterSupport implements MessageEngineMXBean {
    private final Message msg = Echo.msg;
    private long sequenceNumber = 1;

    public MessageEngine(){
        addNotificationListener(new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handback) {
                System.out.println("***Handling new notification***");
                System.out.println("Message : " + notification.getMessage());
                System.out.println("Seq : " + notification.getSequenceNumber());
                System.out.println("*******************************");
            }
        }, null, null);
    }

    @Override
    public void stop() {
        Echo.running = false;
    }

    @Override
    public boolean isPaused() {
        return Echo.pause;
    }

    @Override
    public void pause(boolean pause) {
        Notification n = new AttributeChangeNotification(this,
                sequenceNumber++, System.currentTimeMillis(), "Pause Changed",
                "Paused", "boolean", Echo.pause, pause);
        Echo.pause = pause;
        this.sendNotification(n);
    }

    @Override
    public Message getMessage() {
        return Echo.msg;
    }

    @Override
    public void changeMessage(Message m) {
        this.msg.setTitle(m.getTitle());
        this.msg.setBody(m.getBody());
        this.msg.setBy(m.getBy());
    }

    @Override
    public MBeanNotificationInfo[] getNotificationInfo() {
        String[] types = new String[]{
                AttributeChangeNotification.ATTRIBUTE_CHANGE
        };

        String name = AttributeChangeNotification.class.getName();
        String desc = "An attribute of this MBean has changed";
        MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, desc);
        return new MBeanNotificationInfo[]{info};
    }
}
